import { login, logout, getInfo } from "@/api/sys/user";
import { getToken, setToken, removeToken, removeRolesToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [], // 角色权限控制按钮显示
    menus: [], // 菜单权限
    isAdmin: false
  };
};

const state = getDefaultState();
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ISADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles; // 角色权限
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus; // 菜单权限
  },
};

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const token = response.data;
          commit("SET_TOKEN", token); // vuex存储token
          setToken(token); // cookie存储token
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const data = response.data;
          if (!data) {
            return reject("请重新登录!");
          }
          const { name, avatar, roles, menus } = data;
          if (!menus || menus.length <= 0) {
            reject("getInfo: roles must be a non-null array!");
          }
          commit("SET_NAME", name);
          commit("SET_ISADMIN", name === "guaguaAdmin");
          commit("SET_AVATAR", avatar);
          commit("SET_ROLES", roles); // 角色权限
          commit("SET_MENUS", menus); // 菜单权限
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken();
      removeRolesToken();
      resetRouter();
      commit("RESET_STATE");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken();
      removeRolesToken();
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
